package com.hzlh.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 该类的定义说明、使用范围
 * @Author: link
 * @Date: Created in 2021/6/8 19:31
 * @Version:产品版本号
 */
public class GetDistanceUtils {
    private static final double EARTH_RADIUS = 6378.137;
    public static final double Ea = 6378137;     //   赤道半径
    public static final double Eb = 6356725;     //   极半径


    /**
     * 根据经纬度查询距离(单位:km)
     *
     * @param lng1 经度
     * @param lat1 纬度
     * @param lng2 经度
     * @param lat2 纬度
     * @return 两点间距离(单位:km)
     */
    public static double GetDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }



    private static List<Double> GetlatLon(double LAT, double LON, double distance, double angle) {
        List<Double> list = new ArrayList<>();
        double dx = distance * 1000 * Math.sin(angle * Math.PI / 180.0);
        double dy = distance * 1000 * Math.cos(angle * Math.PI / 180.0);
        double ec = Eb + (Ea - Eb) * (90.0 - LAT) / 90.0;
        double ed = ec * Math.cos(LAT * Math.PI / 180);
        double newLon = (dx / ed + LON * Math.PI / 180.0) * 180.0 / Math.PI;
        double newLat = (dy / ec + LAT * Math.PI / 180.0) * 180.0 / Math.PI;
        list.add(newLon);
        list.add(newLat);
        return list;
    }

    /**
     * 计算最大最小经纬度
     * @param centorlatitude
     * @param centorLogitude
     * @param distance (km)
     */
    public static Map<String, Double> GetRectRange(double centorlatitude, double centorLogitude, double distance) {
        Map<String, Double> map = new HashMap<>();
        double maxLat = GetlatLon(centorlatitude, centorLogitude, distance, 0).get(1);
        double minLat = GetlatLon(centorlatitude, centorLogitude, distance, 180).get(1);
        double maxLon = GetlatLon(centorlatitude, centorLogitude, distance, 90).get(0);
        double minLon = GetlatLon(centorlatitude, centorLogitude, distance, 270).get(0);
        map.put("maxLon",maxLon);
        map.put("minLon",minLon);
        map.put("maxLat",maxLat);
        map.put("minLat",minLat);
        return map;
    }
}
